import { useFetch,useRuntimeConfig,createError} from 'nuxt/app'
import { computed } from 'vue'
import type { UseFetchOptions } from 'nuxt/app'
import { useToken } from '../composables/useToken'

interface ApiResponse<T> {
  code: number
  data: T
  message: string
}

export function useApi<T>(
  url: string,
  options: UseFetchOptions<ApiResponse<T>> = {}
) {
  const config = useRuntimeConfig()
  
  return useFetch<ApiResponse<T>>(url, {
    baseURL: computed<string>(() => config.public.apiBase as string),
    ...options,
    onRequest({ options }) {
      options.headers = new Headers({
        'Authorization': `Bearer ${useToken()}`,
        ...options.headers
      })
    },
    onResponse({ response }) {
      if (!response._data) {
        throw createError({
          statusCode: 500,
          statusMessage: 'No response data received'
        })
      }
      if (response._data.code !== 200) {
        throw createError({
          statusCode: response._data.code,
          statusMessage: response._data.message || 'Unknown error occurred'
        })
      }
    },
    onResponseError({ response }) {
      throw createError({
        statusCode: response.status,
        statusMessage: response.statusText
      })
    }
  })
}

